package com.vi.hcnetsdk.simpleapp;

import android.content.Context;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.provider.MediaStore;
import com.google.android.material.snackbar.Snackbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import static android.app.Activity.RESULT_OK;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ConfigFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ConfigFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ConfigFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public final static String DEMOTAG = "SimpleDemo";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private DataModal.NoticeData nd;

    private OnFragmentInteractionListener mListener;


    private TextView tv;

    private EditText[] et = new EditText[10];

    public ConfigFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ConfigFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ConfigFragment newInstance(String param1, String param2) {
        ConfigFragment fragment = new ConfigFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_config, container, false);

        tv = (TextView) view.findViewById(R.id.status_out);

        nd = new DataModal.NoticeData();
        Button btn_call_elevator = (Button)view.findViewById(R.id.btn_call_elevator);
        btn_call_elevator.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View view) {
                String str = DeviceManage.getInstance().CallEvaluator();
                if( str!= null){
                    //正常操作
                    Snackbar.make(view, "呼叫电梯操作成功", Snackbar.LENGTH_SHORT).show();
                    tv.setText(str);
                }
                else {
                    Snackbar.make(view, "呼叫电梯操作失败，错误码：" + DeviceManage.getInstance().GetLastError(), Snackbar.LENGTH_SHORT).show();
                }
            }
        }
        );

        Button btn_sos_trigger = (Button)view.findViewById(R.id.btn_call_sos_trigger);
        btn_sos_trigger.setOnClickListener(new Button.OnClickListener(){
             @Override
             public void onClick(View view) {
                 String str = DeviceManage.getInstance().SOSAlarmTrigger();
                 if( str!= null){
                     //正常操作
                     Snackbar.make(view, "SOS报警触发操作成功", Snackbar.LENGTH_SHORT).show();
                     tv.setText(str);
                 }
                 else {
                     Snackbar.make(view, "SOS报警触发操作失败，错误码：" + DeviceManage.getInstance().GetLastError(), Snackbar.LENGTH_SHORT).show();
                 }
             }
         }
        );

        Spinner spin = (Spinner) view.findViewById(R.id.spinner_notice_level);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( view.getContext(), R.array.noticelevel_arry, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(adapter);
        spin.setOnItemSelectedListener(ItemSelect_listener);

        et[0] = (EditText) view.findViewById(R.id.et_notice_time);
        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        et[0].setText(str);

        et[1] = (EditText) view.findViewById(R.id.et_notice_number);
        et[2] = (EditText) view.findViewById(R.id.et_notice_title);
        et[3] = (EditText) view.findViewById(R.id.et_notice_details);
        et[4] = (EditText) view.findViewById(R.id.et_notice_picture1);
        et[5] = (EditText) view.findViewById(R.id.et_notice_picture2);
        et[6] = (EditText) view.findViewById(R.id.et_notice_picture3);
        et[7] = (EditText) view.findViewById(R.id.et_notice_picture4);
        et[8] = (EditText) view.findViewById(R.id.et_notice_picture5);
        et[9] = (EditText) view.findViewById(R.id.et_notice_picture6);

        Button openPicFile = (Button)view.findViewById(R.id.btn_add1);
        openPicFile.setOnClickListener(AddPic_ClickListenr);
        openPicFile = (Button)view.findViewById(R.id.btn_add2);
        openPicFile.setOnClickListener(AddPic_ClickListenr);
        openPicFile = (Button)view.findViewById(R.id.btn_add3);
        openPicFile.setOnClickListener(AddPic_ClickListenr);
        openPicFile = (Button)view.findViewById(R.id.btn_add4);
        openPicFile.setOnClickListener(AddPic_ClickListenr);
        openPicFile = (Button)view.findViewById(R.id.btn_add5);
        openPicFile.setOnClickListener(AddPic_ClickListenr);
        openPicFile = (Button)view.findViewById(R.id.btn_add6);
        openPicFile.setOnClickListener(AddPic_ClickListenr);

        Button btn_notice_data = (Button)view.findViewById(R.id.btn_notice_data_download);
        btn_notice_data.setOnClickListener(new Button.OnClickListener(){
               @Override
               public void onClick(View view) {
                   if(nd == null) {
                       nd = new DataModal.NoticeData();
                   }

                   String time = et[0].getText().toString();
                   Date d = StringToDate(time);
                   Calendar calendar = Calendar.getInstance();
                   calendar.setTime(d);
                   nd.year = calendar.get(Calendar.YEAR);
                   nd.month = calendar.get(Calendar.MONTH) + 1;
                   nd.day = calendar.get(Calendar.DAY_OF_MONTH);
                   nd.hour = calendar.get(Calendar.HOUR_OF_DAY);
                   nd.minute = calendar.get(Calendar.MINUTE);
                   nd.second = calendar.get(Calendar.SECOND);

                   Log.i(DEMOTAG, "Time : "+nd.year + "-" +  nd.month + "-" +  nd.day  + " " + nd.hour + ":" + nd.minute + ":" + nd.second);

                   nd.noticeNumber = et[1].getText().toString();
                   nd.noticeTheme = et[2].getText().toString();
                   nd.noticeDetail = et[3].getText().toString();

                   boolean ret = DeviceManage.getInstance().SetNoticeData(nd);
                   if(ret){
                       //正常操作
                       Snackbar.make(view, "公告信息下发成功", Snackbar.LENGTH_SHORT).show();
                   }
                   else {
                       Snackbar.make(view, "公告信息下发失败，错误码：" + DeviceManage.getInstance().GetLastError(), Snackbar.LENGTH_SHORT).show();
                   }
               }
           }
        );

        return view;
    }

    private Button.OnClickListener AddPic_ClickListenr = new Button.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
            intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
            // intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setAction(Intent.ACTION_PICK);

            int id = view.getId();
            switch (id)
            {
                case R.id.btn_add1:
                    startActivityForResult(intent, 1);
                    break;
                case R.id.btn_add2:
                    startActivityForResult(intent, 2);
                    break;
                case R.id.btn_add3:
                    startActivityForResult(intent, 3);
                    break;
                case R.id.btn_add4:
                    startActivityForResult(intent, 4);
                    break;
                case R.id.btn_add5:
                    startActivityForResult(intent, 5);
                    break;
                case R.id.btn_add6:
                    startActivityForResult(intent, 6);
                    break;
                default:
                    break;
            }
        }
    };

    private String getFilePath(Context ct, Intent data)
    {
        if (data != null) {
            Uri uri = data.getData();
            if (!TextUtils.isEmpty(uri.getAuthority())) {
                Cursor cursor = ct.getContentResolver().query(uri,
                        new String[] { MediaStore.Images.Media.DATA },null, null, null);
                if (null == cursor) {
                    Toast.makeText(ct, "图片没找到", Toast.LENGTH_SHORT).show();
                    return null;
                }
                cursor.moveToFirst();
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();
                return path;
            } else {
                String path = uri.getPath();
                return path;
            }
        }else{
            Toast.makeText(ct, "图片没找到", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {

//            ContentResolver cr = this.getActivity().getContentResolver();
//            Uri selectedImage = data.getData();
//            Log.i(DEMOTAG,"selectedImage "+selectedImage.toString());
//            String[] filePathColumns = { MediaStore.Images.Media.DATA };
//            Cursor cursor = cr.query(selectedImage, filePathColumns, null, null,
//                    null);
//            cursor.moveToFirst();
//            int index = cursor.getColumnIndex(filePathColumns[0]);
//            String picturePath = cursor.getString(index);// 取出图片路径
//            Log.i(DEMOTAG, "图片路径" + picturePath);
//            cursor.close();
            String picturePath  = getFilePath(this.getActivity(), data);
            Log.i(DEMOTAG, "图片路径" + picturePath);
            //4-9
            et[requestCode + 3].setText(picturePath);

            try {
                //Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                InputStream in = new FileInputStream(picturePath);
                nd.stream[requestCode - 1] = new byte[in.available()];
                in.read( nd.stream[requestCode - 1]);
                nd.picNum += 1;
                nd.len[requestCode - 1] = in.available();
                in.close();
            } catch (IOException e) {
                Log.e("Exception", e.getMessage(),e);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private Date StringToDate(String s){
        Date time=null;
        SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            time=sd.parse(s);
        } catch (java.text.ParseException e) {
            Log.i(DEMOTAG, "输入的日期格式有误！");
            e.printStackTrace();
        }
        return time;
    }

    private Spinner.OnItemSelectedListener ItemSelect_listener = new Spinner.OnItemSelectedListener(){
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            nd.noticeLevel = position + 1;
        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    };

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
